import HTable from '../../index.vue'
import { isEmpty } from 'lodash-es';
import { ref, type FunctionalComponent, unref, nextTick, type Ref } from 'vue'
export const useTable = () => {
  type HTableInstance = InstanceType<typeof HTable>
  const hTableRef = ref<HTableInstance>({} as HTableInstance)
  async function getTableInstance() {
    await nextTick();
    const table = unref(hTableRef);
    if (isEmpty(table)) {
      console.error('未获取表格实例!');
    }
    return table;
  }
  const methods = new Proxy<Ref<InstanceType<typeof HTable>>>(hTableRef, {
    get(target, key: string) {
      if (Reflect.has(target, key)) {
        return unref(target);
      }
      if (target.value && Reflect.has(target.value, key)) {
        return Reflect.get(target.value, key);
      }
      return async (...rest: any) => {
        const table: any = await getTableInstance();
        return table?.[key]?.(...rest);
      };
    },
  });
  const hTableRender: FunctionalComponent = (props, { attrs, slots }) => {
    return <HTable ref={hTableRef} {...{ ...attrs, ...props, ...props }}
      v-slots={slots}></HTable>
  }
  console.log(hTableRef.value?.refresh, 123)
  return [hTableRender, unref(methods)]
}
